package com.gee.spring.cloud.data.transform.core.center.config.handler;

import cn.hutool.core.util.HexUtil;
import com.gee.spring.cloud.common.core.api.result.ApiResult;
import com.gee.spring.cloud.common.core.entity.center.config.Frame;
import com.gee.spring.cloud.common.starter.config.event.CenterConfigEventHandler;
import com.gee.spring.cloud.common.starter.feign.center.config.FrameClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gepengjun
 * @since 2024/3/19 14:38
 */
@Component
public class FrameHandler extends CenterConfigEventHandler<Frame> {

    private final ConcurrentHashMap<Long, Frame> FRAME_TYPE_MAP = new ConcurrentHashMap<>();

    @Autowired
    private FrameClient frameClient;

    public Frame getById(Long id){
        return FRAME_TYPE_MAP.computeIfAbsent(id, typeId -> frameClient.getById(typeId).getData());
    }

    @Override
    public void handlerUpdate(List<Frame> dataList, List<Frame> oldList) {
        dataList.forEach(frame -> FRAME_TYPE_MAP.computeIfPresent(frame.getId(), (id, old) -> frame));
    }

    @Override
    public void handlerDelete(List<Frame> oldList) {
        oldList.forEach(device -> FRAME_TYPE_MAP.remove(device.getId()));
    }

    public Frame getByBid(long bid) {
        Optional<Frame> frameOptional = FRAME_TYPE_MAP.values().stream()
                .filter(frame ->bid == frame.getBid())
                .findFirst();
        if (frameOptional.isPresent()){
            return frameOptional.get();
        }else {
            ApiResult<Frame> frameApiResult = frameClient.getByBid(bid);
            Frame frame = frameApiResult.getData();
            if (frameApiResult.isSuccess() && frame != null){
                FRAME_TYPE_MAP.put(frame.getId(), frame);
            }else {
                throw new RuntimeException("根据卫星标识["+ HexUtil.toHex(bid)+"]未获取到卫星 ");
            }
            return frame;
        }
    }
}
